package com.idenger.modules.edu.mobileWeb.user;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.idenger.modules.edu.entity.common.BaseResponseMsg;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.idenger.common.sms.SmsConstants;
import com.idenger.common.sms.TemplateSMS;
import com.idenger.common.utils.StringUtils;
import com.idenger.common.utils.TokenProcessor;
import com.idenger.common.web.BaseController;
import com.idenger.modules.edu.entity.common.ResponseMsg;
import com.idenger.modules.edu.entity.smsrecord.EduSmsRecord;
import com.idenger.modules.edu.entity.user.EduUser;
import com.idenger.modules.edu.entity.user.UserToken;
import com.idenger.modules.edu.service.course.EduVideoHistoryService;
import com.idenger.modules.edu.service.enroll.EduEnrollService;
import com.idenger.modules.edu.service.exercisehistory.EduExerciseHistoryService;
import com.idenger.modules.edu.service.income.EduIncomeService;
import com.idenger.modules.edu.service.order.EduOrderService;
import com.idenger.modules.edu.service.smsrecord.EduSmsRecordService;
import com.idenger.modules.edu.service.user.EduUserService;
import com.idenger.modules.edu.service.user.UserTokenService;
import com.idenger.modules.edu.web.comm.Constant;
import com.idenger.modules.sys.entity.User;
import com.idenger.modules.sys.utils.UserUtils;

@Controller
@RequestMapping(value = "${mobilePath}/edu/user/eduUser")
public class MUserController  extends BaseController{
	@Autowired
	private EduSmsRecordService smsRecordService;
	@Autowired
	private EduUserService eduUserService;
	@Autowired
	private UserTokenService userTokenService;
	@Autowired
	private EduEnrollService eduEnrollService;
	@Autowired
	private EduOrderService eduOrderService;
	@Autowired
	private EduIncomeService eduIncomeService;
	@Autowired
	private EduVideoHistoryService eduVideoHistoryService;
	@Autowired
	private EduExerciseHistoryService eduExerciseHistoryService;
	
	@ModelAttribute
	public EduUser get(@RequestParam(required=false) String id) {
		EduUser entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = eduUserService.get(id);
		}
		if (entity == null){
			entity = new EduUser();
		}
		return entity;
	}

	protected synchronized String getUUIDStr(){
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	/***
	 * 注册
	 * @param eduUser
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "signUp")
	public String signUp(EduUser eduUser,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		List<EduUser> list = eduUserService.findList(eduUser);
		if(list.size()>0){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("该账号已经注册过");
			return renderString(response, baseResponseMsg);
		}
		User user = UserUtils.getUser();
		eduUser.setCreateBy(user);
		eduUser.setUpdateBy(user);
		//密码md5加密
		eduUser.setPassword(DigestUtils.md5Hex(eduUser.getPassword()));
		eduUser.setImage(Constant.USER_DEFAULT_IMAGE);
		eduUser.setUserType(Constant.USER_TYPE_PC);//标记为pc端注册用户
		eduUser.setCreateDate(new Date());
		eduUserService.save(eduUser);
		String tokenId = addToken(eduUser.getId(), eduUser);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData(tokenId);
		return renderString(response, baseResponseMsg);
	}
	
	/***
	 * 验证手机号是否已经注册过了
	 * @return
	 */
	@RequestMapping(value = "verificationPhone")
	public String verificationPhone(EduUser eduUser,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		EduUser eduUser2 =  eduUserService.findByAccount(eduUser);
		if(eduUser2 != null){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("该手机已经注册过了");
			return renderString(response, baseResponseMsg);
		}
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData("可以注册");
		return renderString(response, baseResponseMsg);
	}
	
	//发送短信验证码
	@RequestMapping(value = "sendSMS")
	public String sendSMS(HttpServletRequest request, HttpServletResponse response, Model model){
		String phone = request.getParameter("phone");
		//发送短信
		String verificationCode = sendTemplateSMS(phone);
		//增加记录
		EduSmsRecord eduSmsRecord = new EduSmsRecord();
		eduSmsRecord.setPhone(phone);
		eduSmsRecord.setContent(verificationCode);
		eduSmsRecord.setStatus(Constant.SMS_VERIFICATION_NOT);
		//将过期时间设置为两分钟之后
		Calendar expireDTime = Calendar.getInstance();
		expireDTime.add(Calendar.MINUTE, 2);
		Date expireD = expireDTime.getTime();
		eduSmsRecord.setExpiryDate(expireD);
		User user = UserUtils.getUser();
		eduSmsRecord.setCreateBy(user);
		eduSmsRecord.setUpdateBy(user);
		smsRecordService.save(eduSmsRecord);
		BaseResponseMsg baseResponseMsg;
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData("smsRecordId",eduSmsRecord.getId());
		return renderString(response, baseResponseMsg);
	}
	
	/***
	 * 验证
	 * @param eduSmsRecord
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "verification")
	public String verification(EduSmsRecord eduSmsRecord,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		String phone = request.getParameter("phone");
		String id = request.getParameter("id");
		String content = request.getParameter("content");
		EduSmsRecord eduSmsRecord2 = smsRecordService.get(id);
		if(eduSmsRecord2 == null){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("验证失败");
			return renderString(response, baseResponseMsg);
		}
		if(!phone.equals(eduSmsRecord2.getPhone())){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("2", "error"));
			baseResponseMsg.addData("手机号与之前不一致");
			return renderString(response, baseResponseMsg);
		}
		if(!content.equals(eduSmsRecord2.getContent())){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("3", "error"));
			baseResponseMsg.addData("验证码错误");
			return renderString(response, baseResponseMsg);
		}
		if("1".equals(eduSmsRecord2.getStatus())){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("4", "error"));
			baseResponseMsg.addData("验证码已过期");
			return renderString(response, baseResponseMsg);
		}
		Date nowDate = new Date();
		if(eduSmsRecord2.getExpiryDate().getTime()<nowDate.getTime()){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("4", "error"));
			baseResponseMsg.addData("验证码已过期");
			return renderString(response, baseResponseMsg);
		}
		eduSmsRecord2.setStatus(Constant.SMS_VERIFICATION_YES);
		smsRecordService.save(eduSmsRecord2);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData("验证通过");
		return renderString(response, baseResponseMsg);
	}
	
	/***
	 * 登录
	 * @param eduUser
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "signIn")
	public String signIn(EduUser eduUser,HttpServletRequest request, HttpServletResponse response, Model model){
		//用手机号登录
		if("0".equals(eduUser.getLoginType())){
			eduUser.setPhone(eduUser.getAccount());
		}
		//用身份证登录
		if("1".equals(eduUser.getLoginType())){
			eduUser.setIdCard(eduUser.getAccount());
		} 
//		if("2".equals(eduUser.getLoginType())){
//			eduUser.setLoginName(eduUser.getAccount());
//		}
		eduUser.setPassword(DigestUtils.md5Hex(eduUser.getPassword()));
		//用手机号登录
		User user = UserUtils.getUser();
		EduUser eduUser2 =  eduUserService.findByAccount(eduUser);
		BaseResponseMsg baseResponseMsg;
		if(eduUser2 == null){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("该账号不存在");
			return renderString(response, baseResponseMsg);
		}
		if(!eduUser.getPassword().equals(eduUser2.getPassword())){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("密码错误");
			return renderString(response, baseResponseMsg);
		}
		String tokenId = addToken(eduUser2.getId(), eduUser2);
		Map map = new HashMap();
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		eduUser2.setPassword(null);
		map.put("tokenId", tokenId);
		map.put("eduUser", eduUser2);
		baseResponseMsg.addData(map);
		return renderString(response, baseResponseMsg);
	}
	
	public String sendTemplateSMS(String phone){
		 int verificationCode;//定义两变量
         Random ne=new Random();//实例化一个random的对象ne
         verificationCode=ne.nextInt(9999-1000+1)+1000;//为变量赋随机值1000-9999
       //组装模板参数值
 		String[] dataArray = new String[] {"《" +"注册验证,验证码的值是"+ "》" , " " + verificationCode};
         TemplateSMS templateSms = new TemplateSMS();
 		templateSms.prepare();
 		templateSms.sendTemplateSMS(phone, SmsConstants.SMS_TEMPLATE_ID_001, dataArray);
 		return verificationCode+"";
	}
	
	
	private String addToken(String id, EduUser auth) {
		UserToken token = userTokenService.queryUserTokenByUserId(String.valueOf(auth.getId()));
		if (token != null) {
            token.setValid(0);
            userTokenService.updateUserToken(token);
        }
		String tokenId = TokenProcessor.getInstance().generateToken(String.valueOf(auth.getId()), true);// 生成新的token
		UserToken newToken = new UserToken();
		newToken.setUserId(String.valueOf(auth.getId()));
		newToken.setToken(tokenId);
		newToken.setPhone(id);
		newToken.setModifyTime(new Date());
		newToken.setUuid(getUUIDStr());
		newToken.setValid(1);
		userTokenService.addUserToken(newToken);  // 生成新的token记录
		return tokenId;
	}
	
	/***
	 * 微信用户绑定手机号
	 * @param eduUser
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "bind")
	public String bind(EduUser eduUser,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		//获取登录者信息eduUser2
		EduUser eduUser3 = (EduUser) request.getAttribute("currentUser");
		EduUser currentUser = eduUserService.get(eduUser3.getId());
		String phone = request.getParameter("phone");
		if(StringUtils.isBlank(phone)){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("手机号不能为空");
			return renderString(response, baseResponseMsg);
		}
		EduUser eduUserForPhone = new EduUser();
		eduUserForPhone.setPhone(phone);
		EduUser eduUser2 = eduUserService.getByPhone(eduUserForPhone);
		//如果为空，则该手机号还未注册过，只需要给微信的账号加一个手机号即可
		if(eduUser2 == null){
			currentUser.setPhone(phone);
			eduUserService.save(currentUser);
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
			baseResponseMsg.addData(Constant.USER_NO_DETAIL);
			return renderString(response, baseResponseMsg);
		}
		if(StringUtils.isNotBlank(eduUser2.getLoginName())){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("该手机号已经绑定过了");
			return renderString(response, baseResponseMsg);
		}
		//如果不为空，则需要将手机号登录的账号的信息复制给微信的账号 
		currentUser.setRealName(eduUser2.getRealName());
		currentUser.setSex(eduUser2.getSex());
		currentUser.setAge(eduUser2.getAge());
		currentUser.setPhone(phone);
		currentUser.setImage(eduUser2.getImage());
		currentUser.setIdCard(eduUser2.getIdCard());
		currentUser.setEmail(eduUser2.getEmail());
		currentUser.setNickname(eduUser2.getNickname());
		currentUser.setBirth(eduUser2.getBirth());
		currentUser.setIntroduce(eduUser2.getIntroduce());
		currentUser.setProvince(eduUser2.getProvince());
		currentUser.setCity(eduUser2.getCity());
		currentUser.setCounty(eduUser2.getCounty());
		currentUser.setPassword(eduUser2.getPassword());
		eduUserService.save(currentUser);
		//将原本的账号下的订单转移到微信的账号 TODO
		eduEnrollService.updateEnrollForUserId(currentUser.getId(), eduUser2.getId());
		eduOrderService.updateOrderForUserId(currentUser.getId(), eduUser2.getId());
		eduIncomeService.updateIncomeForUserId(currentUser.getId(), eduUser2.getId());
		eduVideoHistoryService.updateHistoryForUserId(currentUser.getId(), eduUser2.getId());
		eduExerciseHistoryService.updateHistoryForUserId(currentUser.getId(), eduUser2.getId());
		//删除原来的账号
		eduUserService.delete(eduUser2);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData(Constant.USER_YES_DETAIL);
		return renderString(response, baseResponseMsg);
	}
	
	
	/***
	 * 修改用户信息
	 * @param eduUser
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "update")
	public String update(EduUser eduUser,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		EduUser currentUser = (EduUser) request.getAttribute("currentUser");
		eduUserService.save(eduUser);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData("用户信息修改成功");
		return renderString(response, baseResponseMsg);
	}
	
	/***
	 * 修改密码
	 * @param eduUser
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "updatePwd")
	public String updatePwd(EduUser eduUser,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		EduUser currentUser = (EduUser) request.getAttribute("currentUser");
		EduUser eduUser2 = eduUserService.get(eduUser.getId());
		String oldPassword = request.getParameter("oldPassword");
		oldPassword = DigestUtils.md5Hex(oldPassword);
			if(!eduUser2.getPassword().equals(oldPassword)){
				baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
				baseResponseMsg.addData("密码错误");
				return renderString(response, baseResponseMsg);
			}
			//密码md5加密
		eduUser.setPassword(DigestUtils.md5Hex(eduUser.getPassword()));
		eduUserService.updatePwd(eduUser);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData("密码修改成功");
		return renderString(response, baseResponseMsg);
	}
	@RequestMapping(value = "updatePhone")
	public String updatePhone(EduUser eduUser,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		EduUser currentUser = (EduUser) request.getAttribute("currentUser");
		EduUser eduUser2 =  eduUserService.getByPhone(eduUser);
		if(eduUser2 != null){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("该手机号已经注册过了");
			return renderString(response, baseResponseMsg);
		}
		eduUserService.updatePhone(eduUser);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData("手机号修改成功");
		return renderString(response, baseResponseMsg);
	}
	 
	
	/***
	 * 个人详情
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "get")
	public String get(HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		//获取登录者信息
		EduUser currentUser = (EduUser) request.getAttribute("currentUser");
		EduUser eduUser = eduUserService.get(currentUser);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData(eduUser);
		return renderString(response, baseResponseMsg);
	}
	@RequestMapping(value = "updPwd")
	public String updPwd(EduUser eduUser,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		String phone = request.getParameter("phone");
		String password = request.getParameter("password");
		eduUser.setPhone(phone);
		EduUser eduUser2 =  eduUserService.getByPhone(eduUser);
		if(eduUser2 == null){
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("该用户不存在");
			return renderString(response, baseResponseMsg);
		}
		eduUser2.setPassword(DigestUtils.md5Hex(password));
		eduUserService.save(eduUser2);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData("修改成功");
		return renderString(response, baseResponseMsg);
	}
}
